package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.concurrent.TimeUnit;


import com.probox.common.core.constant.CacheConstants;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.CustomException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.IdUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.DecryptUtil;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.entity.domain.customer.*;
import com.probox.common.entity.mapper.customer.*;
import com.probox.common.entity.query.BaseQuery;
import com.probox.common.entity.service.customer.*;
import com.probox.common.entity.service.job.IOrderInfoService;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerInfoAccount;
import com.probox.customer.api.domain.CustomerInfoAccountVo;
import com.probox.customer.api.domain.CustomerLevel;
import com.probox.common.entity.service.common.SysReginService;
import com.probox.common.entity.service.platfom.IPlatformSmsConfigService;
import com.probox.common.entity.vo.customer.CustomerInfoLevelVo;
import com.probox.common.entity.vo.customer.CustomerInfoVo;
import com.probox.common.entity.vo.customer.open.CustomerFundOpenVo;
import com.probox.common.entity.vo.customer.open.CustomerPhoneLoginVo;
import com.probox.platform.api.domain.PlatformSmsApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 客户账号Service业务层处理
 *
 * @author zhusiyu
 * @date 2021-05-25
 */
@Service
@Transactional
public class CustomerInfoAccountServiceImpl extends ServiceImpl<CustomerInfoAccountMapper, CustomerInfoAccount> implements ICustomerInfoAccountService {
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerInfoAccountMapper customerInfoAccountMapper;

    @Autowired
    private CustomerInfoAccountTokenMapper customerInfoAccountTokenMapper;

    @Autowired
    private IPlatformSmsConfigService platformSmsConfigService;

    @Autowired
    private CustomerLevelInfoMapper customerLevelInfoMapper;

    @Autowired
    private CustomerLevelMapper customerLevelMapper;

    @Autowired
    private SysReginService sysReginService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private CustomerFundMapper customerFundMapper;

    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;


    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

    @Autowired
    public RedisService redisService;

    private static String customerInfoKey = CachePrefix.CUSTOMER_INFO_DETAIL;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ICustomerFundStoreService customerFundStoreService;

    @Autowired
    private ICustomerTaskInfoService customerTaskInfoService;

    @Autowired
    private ICustomerFundService customerFundService;

    private static final String customer_no_key = CachePrefix.PRE_GLOABLE + "customer_no_";

    /**
     * 查询客户账号
     *
     * @param customerAccountUid 客户账号ID
     * @return 客户账号
     */
    @Override
    public CustomerInfoAccount selectCustomerInfoAccountById(Long customerAccountUid) {
        return this.getById(customerAccountUid);
    }

    /**
     * 查询客户账号列表
     *
     * @param customerInfoAccount 客户账号
     * @return 客户账号
     */
    @Override
    public List<CustomerInfoAccount> queryList(CustomerInfoAccount customerInfoAccount) {
        QueryWrapper<CustomerInfoAccount> queryWrapper = Wrappers.query();
        return customerInfoAccountMapper.selectList(queryWrapper);
    }

    /**
     * 新增客户账号
     *
     * @param customerInfoAccount 客户账号
     * @return 结果
     */
    @Override
    public boolean insertCustomerInfoAccount(CustomerInfoAccount customerInfoAccount) {

        return this.save(customerInfoAccount);

    }

    /**
     * 修改客户账号
     *
     * @param customerInfoAccount 客户账号
     * @return 结果
     */
    @Override
    public boolean updateCustomerInfoAccount(CustomerInfoAccount customerInfoAccount) {
        customerInfoAccount.setUpdateUser(SecurityUtils.getUserId());
        customerInfoAccount.setUpdateName(SecurityUtils.getUsername());
        customerInfoAccount.setUpdateDate(DateUtil.date());
        return this.updateById(customerInfoAccount);
    }

    /**
     * 批量删除客户账号
     *
     * @param customerAccountUids 需要删除的客户账号ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerInfoAccountByIds(Long[] customerAccountUids) {
        return this.removeByIds(Arrays.asList(customerAccountUids));
    }

    @Override
    public CustomerInfoAccount selectUserByUserName(String username) {
        return customerInfoAccountMapper.selectUserByUserName(username);
    }

    @Override
    public CustomerInfoAccount login(CustomerInfoAccountVo account) {
        logger.info("\n=============登录请求参数：{}=============\n",JSON.toJSONString(account));
        QueryWrapper<CustomerInfoAccount> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("ACCOUNT_NAME", account.getAccountName());
        queryWrapper.eq("ACCOUNT_STATUS", CustomerAccountStatusTypeEnum.start.getKey());
        //update by hds 20210904
        //公众号登录必须取公众号注册的账号拿到openID，因为公众号支付需要openID，H5不需要，H5登录可以取公众号和H5注册的账号，
        String sourcePort = SecurityUtils.getCustomerSourcePort();
        if(CustomerAccountSourePortEnum.allwork.getKey().equals(sourcePort)){
            queryWrapper.eq("SOURCE_PORT", SecurityUtils.getCustomerSourcePort());
        }else if(CustomerAccountSourePortEnum.allwork.getKey().equals(sourcePort) ||
                CustomerAccountSourePortEnum.h5.getKey().equals(sourcePort)){
            queryWrapper.and(
                wrapper -> wrapper.eq("SOURCE_PORT",CustomerAccountSourePortEnum.allwork.getKey())
                    .or().eq("SOURCE_PORT",CustomerAccountSourePortEnum.h5.getKey())
            );
        }
        List<CustomerInfoAccount> list = customerInfoAccountMapper.selectList(queryWrapper);
        logger.info("\n=============获取到的用户账户信息：{}=============\n",JSON.toJSONString(list));
        if (list.size() > 0) {
            CustomerInfoAccount customerInfoAccount = list.get(0);
            boolean isPwd = SecurityUtils.matchesPassword(account.getAccountPassword(), customerInfoAccount.getAccountPassword());
            if (isPwd) {
                if(customerInfoAccount.getLoginNumber() == null){
                    customerInfoAccount.setLoginNumber(0);
                }
                int loginNumber = customerInfoAccount.getLoginNumber()+1;
                customerInfoAccount.setLoginNumber(loginNumber);
                //如果为第一次登录则绑定推荐关系
                if (customerInfoAccount.getLoginNumber() == 1){
                    if (!StringUtils.isEmpty(account.getShareUserToken())) {
                        QueryWrapper<CustomerInfoAccountToken> tokenQueryWrapper = new QueryWrapper<>();
                        tokenQueryWrapper.eq("ACCESS_TOKEN", account.getShareUserToken());
                        tokenQueryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
                        CustomerInfoAccountToken customerInfoAccountToken = customerInfoAccountTokenMapper.selectOne(tokenQueryWrapper);
                        customerInfoAccount.setFromCustomerUid(customerInfoAccountToken.getCustomerUid());
                    }
                    if (account.getSharecustomerUid() != null) {
                        customerInfoAccount.setFromCustomerUid(account.getSharecustomerUid());
                    }
                    customerInfoAccount.setUpdateDate(DateUtil.date());
                    bindRelation(customerInfoAccount.getCustomerUid(),customerInfoAccount.getFromCustomerUid());
                }
                customerInfoAccount.setLoginTime(DateUtil.date());
                this.updateById(customerInfoAccount);
                return customerInfoAccount;
            }
            return null;
        }
        return null;
    }

    /**
     * 保存客户账户信息
     *
     * @param customerInfoAccount
     * @return
     */
    //token的过期时间
    private static final Long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    @Override
    public String saveCustomerAccountInfo(CustomerInfoAccountVo customerInfoAccountvo) {
        DateTime date = DateUtil.date();
        Long accountUid = 0L;
        CustomerInfoAccount accountInfo = new CustomerInfoAccount();
        //保存客户账户信息
        QueryWrapper<CustomerInfoAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ACCOUNT_NAME", customerInfoAccountvo.getOpenId());
        queryWrapper.last(" order by CUSTOMER_ACCOUNT_UID desc limit 1");
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectOne(queryWrapper);
        if (customerInfoAccount == null) {
            accountInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            accountInfo.setAccountName(customerInfoAccountvo.getOpenId());
            accountInfo.setRegTime(date);
            accountInfo.setRegIp(SecurityUtils.getCustomerClientIp());
            accountInfo.setAccountStatus("1");
            accountInfo.setCreateDate(date);
            accountInfo.setSourcePort(CustomerAccountSourePortEnum.applet.getKey());
            accountInfo.setOpenId(customerInfoAccountvo.getOpenId());
            accountInfo.setUnionId(customerInfoAccountvo.getUnionid());
            if (customerInfoAccountvo.getShareUserToken() != null) {
                QueryWrapper<CustomerInfoAccountToken> tokenQueryWrapper = new QueryWrapper<>();
                tokenQueryWrapper.eq("ACCESS_TOKEN", customerInfoAccountvo.getShareUserToken());
                tokenQueryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
                CustomerInfoAccountToken customerInfoAccountToken = customerInfoAccountTokenMapper.selectOne(tokenQueryWrapper);
                accountInfo.setFromCustomerUid(customerInfoAccountToken.getCustomerUid());
            }
            if (customerInfoAccountvo.getSharecustomerUid() != null) {
                accountInfo.setFromCustomerUid(customerInfoAccountvo.getSharecustomerUid());
            }
            customerInfoAccountMapper.insert(accountInfo);
            accountUid = accountInfo.getCustomerAccountUid();
        } else {
            customerInfoAccount.setUpdateDate(date);
            customerInfoAccountMapper.updateById(customerInfoAccount);
            accountUid = customerInfoAccount.getCustomerAccountUid();
        }

        CustomerInfoAccountVo infoAccountVo = new CustomerInfoAccountVo();
        infoAccountVo.setSessionKey(customerInfoAccountvo.getSessionKey());
        infoAccountVo.setOpenId(customerInfoAccountvo.getOpenId());
        String token = rstToken(infoAccountVo, accountUid);
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        return null;
    }

    //返回token信息
    public String rstToken(CustomerInfoAccountVo infoAccountVo, Long accountUid) {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String CustomerToken = req.getHeader("CustomerToken");
        if (StringUtils.isEmpty(CustomerToken)) {
            //保存token信息
            logger.info("================未找到CustomerToken,重新生成token========================");
            CustomerInfoAccountToken token = new CustomerInfoAccountToken();
            token.setCustomerAccountUid(accountUid);
            token.setCustomerUid(infoAccountVo.getCustomerUid());
            token.setAccessToken(IdUtils.fastUUID());
            token.setClientIp(SecurityUtils.getCustomerClientIp());
            token.setSecretKey(infoAccountVo.getSessionKey());
            token.setDataStatus("1");
            token.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            token.setExpireTime(DateUtils.add(EXPIRE_TIME));
            token.setCreateTime(DateUtil.date());
            token.setOpenId(infoAccountVo.getOpenId());
            token.setSourcePort(CustomerAccountSourePortEnum.applet.getKey());
            customerInfoAccountTokenMapper.insert(token);
            if (token != null) {
                String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token.getAccessToken();
                sops.set(key, JSON.toJSONString(token), EXPIRE_TIME, TimeUnit.MINUTES);
                return token.getAccessToken();
            }
        } else {
            String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + CustomerToken;
            String user = sops.get(key);
            if (!StringUtils.isEmpty(user)) {
                logger.info("================token未过期,刷新token信息========================");
                QueryWrapper<CustomerInfoAccountToken> accountTokenQueryWrapper = new QueryWrapper<>();
                accountTokenQueryWrapper.eq("ACCESS_TOKEN", CustomerToken);
                CustomerInfoAccountToken customerInfoAccountToken = customerInfoAccountTokenMapper.selectOne(accountTokenQueryWrapper);
                customerInfoAccountToken.setClientIp(SecurityUtils.getCustomerClientIp());
                customerInfoAccountToken.setSecretKey(infoAccountVo.getSessionKey());
                customerInfoAccountToken.setExpireTime(DateUtils.add(EXPIRE_TIME));
                customerInfoAccountTokenMapper.updateById(customerInfoAccountToken);
                //更新token数据
                if (customerInfoAccountToken != null) {
                    sops.set(key, JSON.toJSONString(customerInfoAccountToken), EXPIRE_TIME, TimeUnit.MINUTES);
                    return customerInfoAccountToken.getAccessToken();
                }
            } else {
                //保存token信息
                logger.info("================未找到token:" + CustomerToken + ",重新生成token========================");
                CustomerInfoAccountToken token = new CustomerInfoAccountToken();
                token.setCustomerAccountUid(accountUid);
                token.setAccessToken(IdUtils.fastUUID());
                token.setClientIp(SecurityUtils.getCustomerClientIp());
                token.setSecretKey(infoAccountVo.getSessionKey());
                token.setDataStatus("1");
                token.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
                token.setExpireTime(DateUtils.add(EXPIRE_TIME));
                token.setCreateTime(DateUtil.date());
                token.setOpenId(infoAccountVo.getOpenId());
                token.setSourcePort(CustomerAccountSourePortEnum.applet.getKey());
                customerInfoAccountTokenMapper.insert(token);
                if (token != null) {
                    String tokenKey = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token.getAccessToken();
                    sops.set(tokenKey, JSON.toJSONString(token), EXPIRE_TIME, TimeUnit.MINUTES);
                    return token.getAccessToken();
                }
            }
        }
        return null;
    }

    private String createCustomerNo() {
        String time = DateUtil.format(new Date(),"yyMMdd");
        String key = customer_no_key + time;
        String no = String.valueOf(redisService.incr(key, 1L, TimeUnit.DAYS));
        while (no.length()<4){
            no = "0"+no;
        }
        String orderNo = time + no;
        return orderNo;
    }

    /**
     * 获取手机号登录
     *
     * @param customerInfoAccountVo
     */
    @Override
    public String gainCustomerInfo(CustomerInfoAccountVo customerInfoAccountVo) throws Exception {
        String rst = DecryptUtil.decryptS5(customerInfoAccountVo.getEncrypdata(), "utf-8", SecurityUtils.getCustomerSecretKey(), customerInfoAccountVo.getIv());
        JSONObject objJson = JSONObject.parseObject(rst);
        logger.info("objJson=>" + objJson);
        String phone = "";
        if (objJson != null && !StringUtils.isEmpty(objJson.getString("phoneNumber"))) {
            phone = objJson.getString("phoneNumber");
        } else {
            throw new CustomException("获取手机号码失败");
        }
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectById(SecurityUtils.getCustomerAccountUid());
        //新增客户信息
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("PHONE", phone);
        CustomerInfo info = customerInfoMapper.selectOne(queryWrapper);
        Long CustomerUid = null;
        if (info != null) {
            info.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            if (StringUtils.isNotEmpty(customerInfoAccount.getAccountNickName())) {
                info.setCustomerName(customerInfoAccount.getAccountNickName());
            }
            if (StringUtils.isNotEmpty(customerInfoAccount.getAccountHeadImg())) {
                info.setHeadImage(customerInfoAccount.getAccountHeadImg());
            }
            if (StringUtils.isNotEmpty(customerInfoAccount.getSex())){
                info.setSex(customerInfoAccount.getSex());
            }
            if (StringUtils.isNotEmpty(customerInfoAccount.getCity())){
                info.setNation(customerInfoAccount.getNation());
                info.setProvince(customerInfoAccount.getProvince());
                info.setCity(customerInfoAccount.getCity());
                String[] labels = new String[2];
                labels[0] = info.getProvince();
                labels[1] = info.getCity();
                Long[] reginCode = sysReginService.getReginCode(labels);
                if (reginCode != null && reginCode.length > 0) {
                    logger.info("省code=>" + reginCode[0] + "市code=>" + reginCode[1]);
                    info.setProvinceCode(String.valueOf(reginCode[0]));
                    info.setCityCode(String.valueOf(reginCode[1]));
                }
            }

            info.setPhone(phone);
//            info.setCreateTime(DateUtil.date());
            info.setStatus(DataStatus.valid.getKey());
            customerInfoMapper.updateById(info);
            CustomerUid = info.getCustomerUid();
            customerTaskInfoService.finishTask(info,TaskCodeEnum.login_task.toString());
        } else {
            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setCustomerName(customerInfoAccount.getAccountNickName());
            customerInfo.setHeadImage(customerInfoAccount.getAccountHeadImg());
            customerInfo.setSex(customerInfoAccount.getSex());
            customerInfo.setNation(customerInfoAccount.getNation());
            customerInfo.setProvince(customerInfoAccount.getProvince());
            customerInfo.setCity(customerInfoAccount.getCity());
            customerInfo.setCustomerNo(genCustomerNo());
            if (!StringUtils.isEmpty(customerInfo.getProvince()) && !StringUtils.isEmpty(customerInfo.getCity())) {
                String[] labels = new String[2];
                labels[0] = customerInfo.getProvince();
                labels[1] = customerInfo.getCity();
                Long[] reginCode = sysReginService.getReginCode(labels);
                if (reginCode != null && reginCode.length > 0) {
                    logger.info("省code=>" + reginCode[0] + "市code=>" + reginCode[1]);
                    customerInfo.setProvinceCode(String.valueOf(reginCode[0]));
                    customerInfo.setCityCode(String.valueOf(reginCode[1]));
                }
            }
            customerInfo.setPhone(phone);
            customerInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerInfo.setCreateTime(DateUtil.date());
            customerInfo.setStatus(DataStatus.valid.getKey());
            customerInfoMapper.insert(customerInfo);
            CustomerUid = customerInfo.getCustomerUid();
            //根据推荐人id绑定客户推荐关系
            if (customerInfoAccount.getFromCustomerUid() != null && customerInfoAccount.getCustomerUid() == null) {
                //bindRelation(CustomerUid, customerInfoAccount.getFromCustomerUid());
            }
            //初始化客户资金
            initFund(CustomerUid);
            customerTaskInfoService.finishTask(customerInfo,TaskCodeEnum.login_task.toString());
        }


        //更新客户账号信息
        customerInfoAccount.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        customerInfoAccount.setCustomerUid(CustomerUid);
        customerInfoAccount.setPhone(phone);
        customerInfoAccount.setLoginTime(DateUtil.date());
        Integer loginNumber = customerInfoAccount.getLoginNumber();
        if (loginNumber != null) {
            loginNumber += 1;
        } else {
            loginNumber = 1;
        }
        customerInfoAccount.setLoginNumber(loginNumber);
        customerInfoAccount.setUpdateDate(DateUtil.date());
        customerInfoAccountMapper.updateById(customerInfoAccount);

        //更新客户token信息
        String token = updateCustomerToken(CustomerUid, customerInfoAccount.getAccountNickName());
        return token;
    }

    public String updateCustomerToken(Long CustomerUid, String accountNickName) {
        //新增客户账号token信息
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = req.getHeader("CustomerToken");
        logger.info("============开始更新token" + token + "信息,客户信息为=>" + CustomerUid + "============");
        QueryWrapper<CustomerInfoAccountToken> accountTokenQueryWrapper = new QueryWrapper<>();
        accountTokenQueryWrapper.eq("ACCESS_TOKEN", token);
        CustomerInfoAccountToken customerInfoAccountToken = customerInfoAccountTokenMapper.selectOne(accountTokenQueryWrapper);
        customerInfoAccountToken.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        customerInfoAccountToken.setCustomerUid(CustomerUid);
        customerInfoAccountToken.setCreateTime(DateUtil.date());
        customerInfoAccountToken.setCreateName(accountNickName);
//        customerInfoAccountToken.setAccessToken(IdUtils.fastUUID());
        customerInfoAccountTokenMapper.updateById(customerInfoAccountToken);
        if (customerInfoAccountToken != null) {
            //使用这个key为更新
            String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token;
//            String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + newCustomerInfoAccountToken.getAccessToken();
            sops.set(key, JSON.toJSONString(customerInfoAccountToken), EXPIRE_TIME, TimeUnit.MINUTES);
            return customerInfoAccountToken.getAccessToken();
        }
        logger.info("更改后token" + customerInfoAccountToken.getAccessToken());
        return customerInfoAccountToken.getAccessToken();
    }

    //初始化客户资金
    public void initFund(Long customerUid) {
        QueryWrapper<CustomerFund> fundQueryWrapper = new QueryWrapper<>();
        fundQueryWrapper.eq("CUSTOMER_UID", customerUid);
        fundQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        CustomerFund fund = customerFundMapper.selectOne(fundQueryWrapper);
        if (fund == null) {
            fund = new CustomerFund();
            fund.setCustomerUid(customerUid);
            fund.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            fund.setCreateTime(DateUtil.date());

            fund.setFreezeScore(0L);
            fund.setScore(0L);
            fund.setAllScore(0L);


            fund.setUpdateTime(fund.getCreateTime());

            fund.setRedBag(0L);
            fund.setAllRedBag(0L);
            fund.setFreezeRedBag(0L);

            fund.setAllWithdraw(0L);

            fund.setBalance(0L);
            fund.setAllBalance(0L);

            fund.setAllFansSecond(0);
            fund.setAllFans(0);

            fund.setProfit(0L);
            fund.setAllProfit(0L);
            fund.setFreezeProfit(0L);

            customerFundMapper.insert(fund);
        }
        //更新客户等级
        //customerLevelInfoService.getCustomerBindLevelInfo(customerUid, fund.getFundUid(), SecurityUtils.getCustomerPlatformUid());
    }

    private void bindRelation(Long CustomerUid, Long fromCustomerUid) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(CustomerUid);
        CustomerInfo customerInfoFather = customerInfoMapper.selectById(fromCustomerUid);
        if (customerInfoFather != null) {
            customerInfo.setFatherUid(fromCustomerUid);
            customerInfo.setGrandFatherUid(customerInfoFather.getFatherUid());
            //推荐关系
            if (!StringUtils.isEmpty(customerInfoFather.getParentTree())) {
                customerInfo.setParentTree(customerInfoFather.getParentTree() + fromCustomerUid + "/");
            } else {
                customerInfo.setParentTree("/" + fromCustomerUid + "/");
            }
            //更新粉丝数量
            updateFansNumber(fromCustomerUid);
            customerInfoMapper.updateById(customerInfo);
        }


    }

    /**
     * 更新粉丝数量
     */
    public void updateFansNumber(Long fromCustomerUid) {
        CustomerInfo customerInfoFather = customerInfoMapper.selectById(fromCustomerUid);
        //客户资金表新增粉丝数据
        QueryWrapper<CustomerFund> fundQueryWrapper = new QueryWrapper<>();
        fundQueryWrapper.eq("CUSTOMER_UID", fromCustomerUid);
        CustomerFund fundInfo = customerFundMapper.selectOne(fundQueryWrapper);
        if (fundInfo != null) {
            //更新粉丝数
            Integer allFans = fundInfo.getAllFans();
            allFans = allFans + 1;
            fundInfo.setAllFans(allFans);
            fundInfo.setUpdateTime(DateUtil.date());
            customerFundMapper.updateById(fundInfo);
            //更新祖级客户数
            if (customerInfoFather.getFatherUid() != null) {
                Long fatherUid = customerInfoFather.getFatherUid();
                QueryWrapper<CustomerFund> fatherQueryWrapper = new QueryWrapper<>();
                fatherQueryWrapper.eq("CUSTOMER_UID", fatherUid);
                CustomerFund fatherFundInfo = customerFundMapper.selectOne(fatherQueryWrapper);
                if (fatherFundInfo != null) {
                    //更新粉丝数
                    Integer allFansSecond = fatherFundInfo.getAllFansSecond();
                    allFansSecond += 1;
                    fundInfo.setAllFansSecond(allFansSecond);
                    fundInfo.setUpdateTime(DateUtil.date());
                    customerFundMapper.updateById(fatherFundInfo);
                }
            }
            //更新客户等级
            //customerLevelInfoService.bindCustoemrLevel(fundInfo.getFundUid(), SecurityUtils.getCustomerPlatformUid());
            if (customerInfoFather.getFatherUid() != null) {
                updateFansNumber(customerInfoFather.getFatherUid());
            }
        } else {
            CustomerFund customerFund = new CustomerFund();
            customerFund.setCustomerUid(fromCustomerUid);
            customerFund.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerFund.setAllFans(1);
            customerFund.setCreateTime(DateUtil.date());
            customerFundMapper.insert(customerFund);
            //customerLevelInfoService.bindCustoemrLevel(customerFund.getFundUid(), SecurityUtils.getCustomerPlatformUid());
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    public CustomerInfoVo getCustomerInfo() {
        logger.info("===================================开始获取用户信息=====================================");
        Long customerId = SecurityUtils.getCustomerUid();
        String customerInfoKey = CachePrefix.CUSTOMER_INFO_DETAIL + customerId;
        CustomerInfoVo customerInfoVo = redisService.getCacheObject(customerInfoKey);
        if (ObjectUtil.isEmpty(customerInfoVo)) {
            customerInfoVo = new CustomerInfoVo();
            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
//            CustomerInfoVo customerInfoVo = new CustomerInfoVo();
            if (customerInfo == null) {
                return customerInfoVo;
            }
            BeanUtils.copyProperties(customerInfo, customerInfoVo);
            if (!StringUtils.isEmpty(customerInfo.getCustomerName())) {
                customerInfoVo.setIsUpdateInfo(true);
            } else {
                customerInfoVo.setIsUpdateInfo(false);
            }
            QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
            levelInfoQueryWrapper.eq("CUSTOMER_UID", customerInfo.getCustomerUid());
            levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
            levelInfoQueryWrapper.last(" order by LEVEL_INFO_ID desc limit 1");
            CustomerLevelInfo customerLevelInfo = customerLevelInfoMapper.selectOne(levelInfoQueryWrapper);
            if (customerLevelInfo != null) {
                CustomerLevel level = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                if(level != null){
                    customerInfoVo.setCustomerGrade(level.getCustomerGrade());
                    customerInfoVo.setCustomerLevelType(level.getCustomerPattern());
                    customerInfoVo.setCustomerIcon(level.getLevelIcon());
                    customerInfoVo.setLevelName(level.getLevelName());
                    customerInfoVo.setExpireTime(customerLevelInfo.getExpireTime());
                    customerInfoVo.setLevelColor(level.getLevelColor());
                    customerInfoVo.setLevelImage(level.getLevelImage());
                    customerInfoVo.setLevelUid(level.getLevelId());
                    customerInfoVo.setLevelIconItalic(level.getLevelIconItalic());
                    customerInfoVo.setLevelIconNo(level.getLevelIconNo());
                }
            }

            CustomerFundOpenVo customerFund = customerInfoService.geCustomerFundInfo();
            if (customerFund != null) {
                customerInfoVo.setAllProfit(customerFund.getAllProfit());
                customerInfoVo.setAllBalance(customerFund.getAllBalance());
                customerInfoVo.setAllScore(customerFund.getAllScore());
                customerInfoVo.setAllRedBag(customerFund.getAllRedBag());
                customerInfoVo.setScore(customerFund.getScore()-customerFund.getFreezeScore());
            }


            redisService.setCacheObject(customerInfoKey, customerInfoVo, RedisService.ThirtySecond, TimeUnit.SECONDS);
        } else {
            logger.info("找到用户id:{}详细信息=>", customerInfoVo.getCustomerUid());
        }
        //判断当前客户账号是否锁定
        Boolean isLockAccount = getIsLockAccount(SecurityUtils.getCustomerUid());
        if (isLockAccount == false) {
            customerInfoVo.setAccountStatus(CustomerAccountStatusTypeEnum.lock.getKey());
        } else {
            customerInfoVo.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
        }
        return customerInfoVo;

    }

    @Override
    public CustomerInfoVo getCustomerSimpleInfo(BaseQuery query) {
        logger.info("===================================开始获取用户信息=====================================");
        Long customerId = SecurityUtils.getCustomerUid();
        String customerInfoKey = CachePrefix.CUSTOMER_SIMPLE_INFO_DETAIL + customerId;
        if (query.getStoreId() != null){
            customerInfoKey=customerInfoKey+"_"+query.getStoreId();
        }
        CustomerInfoVo customerInfoVo = redisService.getCacheObject(customerInfoKey);
        if (ObjectUtil.isEmpty(customerInfoVo)) {
            customerInfoVo = new CustomerInfoVo();
            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
//            CustomerInfoVo customerInfoVo = new CustomerInfoVo();
            if (customerInfo == null) {
                return customerInfoVo;
            }
            customerInfoVo.setCustomerName(customerInfo.getCustomerName());
            customerInfoVo.setHeadImage(customerInfo.getHeadImage());

            QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
            levelInfoQueryWrapper.eq("CUSTOMER_UID", customerInfo.getCustomerUid());
            levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
            levelInfoQueryWrapper.last(" order by LEVEL_INFO_ID desc limit 1");
            CustomerLevelInfo customerLevelInfo = customerLevelInfoMapper.selectOne(levelInfoQueryWrapper);
            if (customerLevelInfo != null) {
                CustomerLevel level = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                if(level != null){
                    customerInfoVo.setCustomerGrade(level.getCustomerGrade());
                    customerInfoVo.setCustomerLevelType(level.getCustomerPattern());
                    customerInfoVo.setCustomerIcon(level.getLevelIcon());
                    customerInfoVo.setLevelName(level.getLevelName());
                    customerInfoVo.setExpireTime(customerLevelInfo.getExpireTime());
                    customerInfoVo.setLevelColor(level.getLevelColor());
                    customerInfoVo.setLevelImage(level.getLevelImage());
                    customerInfoVo.setLevelIconItalic(level.getLevelIconItalic());
                    customerInfoVo.setLevelIconNo(level.getLevelIconNo());
                }
            }
            CustomerFundOpenVo customerFund = customerInfoService.geCustomerFundInfo();
            if (customerFund != null) {
                customerInfoVo.setAllProfit(customerFund.getAllProfit());
                customerInfoVo.setAllBalance(customerFund.getAllBalance());
                customerInfoVo.setAllScore(customerFund.getAllScore());
                customerInfoVo.setAllRedBag(customerFund.getAllRedBag());
                customerInfoVo.setScore(customerFund.getScore()-customerFund.getFreezeScore());
            }

            if (query.getStoreId() != null){
                customerInfoVo.setAllRedBag("0");
                CustomerFundStore fundStore = customerFundStoreService.selectCustomerFund(query.getStoreId(),customerId);
                if (fundStore != null){
                    customerInfoVo.setAllRedBag(MoneyUtils.changeF2Y(fundStore.getRedBag()));
                }
            }


            redisService.setCacheObject(customerInfoKey, customerInfoVo, RedisService.FIVEMINUTE, TimeUnit.SECONDS);
        } else {
            logger.info("找到用户id:{}详细信息=>", customerInfoVo.getCustomerUid());
        }
        return customerInfoVo;
    }

    /**
     * 手机号登录
     *
     * @return
     */
    @Override
    public String PhoneLogin(CustomerPhoneLoginVo customerPhoneLoginVo) {
        PlatformSmsApi platformSmsApi = customerPhoneLoginVo.getPlatformSmsApi();
        platformSmsApi.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        logger.info("手机号登录,当前平台id:" + SecurityUtils.getCustomerPlatformUid());
        platformSmsConfigService.validateSmsCode(platformSmsApi);
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("PHONE", platformSmsApi.getPhone());
        queryWrapper.eq("STATUS", DataStatus.valid.getKey());
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);
        CustomerInfoAccount customerInfoAccount = new CustomerInfoAccount();
        if (customerInfo != null) {
            QueryWrapper<CustomerInfoAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("CUSTOMER_UID", customerInfo.getCustomerUid());
            accountQueryWrapper.eq("ACCOUNT_STATUS", CustomerAccountStatusTypeEnum.start.getKey());
            accountQueryWrapper.eq("SOURCE_PORT", SecurityUtils.getCustomerSourcePort());
            customerInfoAccount = customerInfoAccountMapper.selectOne(accountQueryWrapper);
        }
        //判断是否有客户信息
        Long fromCustomerUid = null;
        Long customerUid = null;
        if (ObjectUtil.isEmpty(customerInfo)) {
            throw new CustomException("手机号或用户名错误");
        }
        //判断是否有账号
        if (ObjectUtil.isEmpty(customerInfoAccount)) {
            throw new CustomException("手机号或用户名错误");
        } else {
            //修改账号信息
            customerInfoAccount.setCustomerUid(customerUid);
            customerInfoAccount.setLoginTime(DateUtil.date());
            int loginNumber = customerInfoAccount.getLoginNumber();
            loginNumber += 1;
            customerInfoAccount.setLoginNumber(loginNumber);
            customerInfoAccount.setUpdateDate(DateUtil.date());
            customerInfoAccountMapper.updateById(customerInfoAccount);
        }
        //初始化客户资金
        initFund(customerInfoAccount.getCustomerUid());


        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String CustomerToken = req.getHeader("CustomerToken");
        String loginToken = sops.get(CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + CustomerToken);
        if (StringUtils.isEmpty(loginToken)) {
            if (customerInfoAccount != null) {
                //保存token信息
                CustomerInfoAccountToken token = new CustomerInfoAccountToken();
                token.setCustomerUid(customerInfoAccount.getCustomerUid());
                token.setCustomerAccountUid(customerInfoAccount.getCustomerAccountUid());
                token.setAccessToken(IdUtils.fastUUID());
                token.setClientIp(SecurityUtils.getCustomerClientIp());
//                  token.setSecretKey(customerInfoAccountvo.getSessionKey());
                token.setDataStatus(DataStatus.valid.getKey());
                token.setExpireTime(DateUtils.add(EXPIRE_TIME));
                token.setCreateTime(DateUtil.date());
                token.setCreateName(customerInfoAccount.getAccountName());
                token.setCreateUser(customerInfoAccount.getCustomerUid());
                token.setOpenId(customerInfoAccount.getOpenId());
//                req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//                String Port = req.getHeader("CustomerPort");
                token.setSourcePort(SecurityUtils.getCustomerSourcePort());
                customerInfoAccountTokenMapper.insert(token);
                if (token != null) {
                    String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token.getAccessToken();
                    sops.set(key, JSON.toJSONString(token), EXPIRE_TIME, TimeUnit.MINUTES);
                    return token.getAccessToken();
                }
            } else {
                throw new CustomException("手机号登录失败");
            }
        } else {
            CustomerInfoAccountToken customerInfoAccountToken = JSONObject.parseObject(loginToken, CustomerInfoAccountToken.class);
            return customerInfoAccountToken.getAccessToken();
        }
        return null;
    }


    /**
     * 通过微信获取手机号
     *
     * @param customerInfoAccountVo
     * @return
     */
    @Override
    public String gainPhone(CustomerInfoAccountVo customerInfoAccountVo) throws Exception {
        String rst = DecryptUtil.decryptS5(customerInfoAccountVo.getEncrypdata(), "utf-8", SecurityUtils.getCustomerSecretKey(), customerInfoAccountVo.getIv());
        JSONObject objJson = JSONObject.parseObject(rst);
        logger.info("objJson=>" + objJson);
        String phone = "";
        if (objJson != null && !StringUtils.isEmpty(objJson.getString("phoneNumber"))) {
            phone = objJson.getString("phoneNumber");
        } else {
            throw new CustomException("获取手机号码失败");
        }
        return phone;
    }

    /**
     * 启动或锁定账号信息
     *
     * @param customerInfo
     * @return
     */
    @Override
    public Boolean updateCustomerAccountStatus(CustomerInfoLevelVo customerInfo) {
        String status = customerInfo.getAccountStatus();
        if (CustomerAccountStatusTypeEnum.start.getKey().equals(customerInfo.getAccountStatus())) {
            customerInfo.setAccountStatus(CustomerAccountStatusTypeEnum.lock.getKey());
        } else {
            customerInfo.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
        }
        UpdateWrapper<CustomerInfoAccount> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("CUSTOMER_UID", customerInfo.getCustomerUid());
        updateWrapper.eq("ACCOUNT_STATUS", status);
        updateWrapper.set("ACCOUNT_STATUS", customerInfo.getAccountStatus());
        return this.update(updateWrapper);
    }

    /**
     * 判断当前客户账号是否锁定
     *
     * @param custoemrUid
     * @return
     */
    @Override
    public Boolean getIsLockAccount(Long custoemrUid) {
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("CUSTOMER_UID", custoemrUid);
        infoAccountQueryWrapper.eq("ACCOUNT_STATUS", CustomerAccountStatusTypeEnum.lock.getKey());
        infoAccountQueryWrapper.select("CUSTOMER_ACCOUNT_UID");
        List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(infoAccountQueryWrapper);
        if (customerInfoAccountList.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public HashMap getCustomerInfoByOpenId(String openID) {
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("OPEN_ID", openID);
        infoAccountQueryWrapper.eq("ACCOUNT_STATUS", CustomerAccountStatusTypeEnum.start.getKey());
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectOne(infoAccountQueryWrapper);
        HashMap rstMap = new HashMap();
        if (customerInfoAccount != null) {
            rstMap.put("accountNickName", customerInfoAccount.getAccountNickName());
            rstMap.put("customerUid", customerInfoAccount.getCustomerUid());
            rstMap.put("openId", customerInfoAccount.getOpenId());
        }
        return rstMap;
    }

    @Override
    public Boolean updateAccountStatusById(CustomerInfoAccount customerInfoAccount) {
        UpdateWrapper<CustomerInfoAccount> infoAccountUpdateWrapper = new UpdateWrapper<>();
        infoAccountUpdateWrapper.eq("CUSTOMER_ACCOUNT_UID", customerInfoAccount.getCustomerAccountUid());
        infoAccountUpdateWrapper.set("ACCOUNT_STATUS", customerInfoAccount.getAccountStatus());
        return this.update(infoAccountUpdateWrapper);
    }

    /**
     * 保存公众号登录返回客户信息
     *
     * @param infoAccountVo
     * @return
     */
    @Override
    public String allworkLogin(CustomerInfoAccountVo infoAccountVo) {
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("ACCOUNT_NAME", infoAccountVo.getOpenId());
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectOne(infoAccountQueryWrapper);
        if (customerInfoAccount == null) {

            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setCustomerName(infoAccountVo.getNickname());
            customerInfo.setHeadImage(infoAccountVo.getHeadimgurl());
            customerInfo.setSex(infoAccountVo.getSex());
            customerInfo.setCustomerNo(genCustomerNo());
            customerInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerInfo.setCreateTime(DateUtil.date());
            customerInfo.setStatus(DataStatus.valid.getKey());
            customerInfoMapper.insert(customerInfo);
            //初始化客户资金
            initFund(customerInfo.getCustomerUid());

            customerFundService.sendJiFen("register",customerInfo.getCustomerUid());

            //新增客户账号信息
            customerInfoAccount = new CustomerInfoAccount();
            customerInfoAccount.setAccountName(infoAccountVo.getOpenId());
            customerInfoAccount.setCustomerUid(customerInfo.getCustomerUid());
//            customerInfoAccount.setAccountNickName(infoAccountVo.getNickname());
            customerInfoAccount.setAccountHeadImg(infoAccountVo.getHeadimgurl());
            customerInfoAccount.setRegTime(DateUtil.date());
            customerInfoAccount.setRegIp(SecurityUtils.getCustomerClientIp());
//            customerInfoAccount.setLoginTime(DateUtil.date());
//            customerInfoAccount.setLoginNumber(0);
            customerInfoAccount.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
            customerInfoAccount.setCreateDate(DateUtil.date());
            customerInfoAccount.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerInfoAccount.setSourcePort(SecurityUtils.getCustomerSourcePort());
            customerInfoAccount.setOpenId(infoAccountVo.getOpenId());
            customerInfoAccount.setUnionId(infoAccountVo.getUnionid());

            String sex = "";
            if (WechatSexEnum.man.getKey().equals(infoAccountVo.getSex())) {
                sex = CustomerSexEnum.man.getKey();
            }
            if (WechatSexEnum.woman.getKey().equals(infoAccountVo.getSex())) {
                sex = CustomerSexEnum.woman.getKey();
            }
            if (WechatSexEnum.unknown.getKey().equals(infoAccountVo.getSex())) {
                sex = CustomerSexEnum.unknown.getKey();
            }
            customerInfoAccount.setSex(sex);
            if (CustomerNationEnum.CN.getKey().equals(infoAccountVo.getCountry())) {
                customerInfoAccount.setNation(CustomerNationEnum.CN.getValue());
            }
            customerInfoAccount.setProvince(infoAccountVo.getProvince());
            customerInfoAccount.setCity(infoAccountVo.getCity());
            customerInfoAccountMapper.insert(customerInfoAccount);
        }
        CustomerInfoAccountVo accountVo = new CustomerInfoAccountVo();
        accountVo.setOpenId(infoAccountVo.getOpenId());
        accountVo.setCustomerUid(customerInfoAccount.getCustomerUid());
        String token = rstToken(accountVo, customerInfoAccount.getCustomerAccountUid());
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        return null;
    }

    /**
     * 客户注册创建账号
     *
     * @param account
     * @return
     */
    @Override
    public Boolean createCustomerAccount(CustomerInfoAccountVo account) {
        String phoneKey = "phone_"+account.getPhone();
        if (redisService.incr(phoneKey,10,TimeUnit.SECONDS)>1L){
            throw new CustomException("该手机号码注册中,请勿重复提交注册！");
        }
        //校验验证码
        PlatformSmsApi platformSmsApi = new PlatformSmsApi();
        platformSmsApi.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        platformSmsApi.setPhone(account.getPhone());
        platformSmsApi.setCode(account.getCode());
        platformSmsConfigService.validateSmsCode(platformSmsApi);
        //验证是否注册过
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        infoAccountQueryWrapper.eq("PHONE", platformSmsApi.getPhone());
        infoAccountQueryWrapper.eq("SOURCE_PORT",SecurityUtils.getCustomerSourcePort());
        CustomerInfoAccount infoAccount = customerInfoAccountMapper.selectOne(infoAccountQueryWrapper);
        if (infoAccount != null) {
            throw new CustomException("该手机号已注册,请使用手机号码登录");
        }
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("PHONE", platformSmsApi.getPhone());
        queryWrapper.eq("STATUS", DataStatus.valid.getKey());
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);
        //判断是否有客户信息
        Long customerUid = null;
        if (ObjectUtil.isEmpty(customerInfo)) {
            customerInfo = new CustomerInfo();
            customerInfo.setCustomerName(account.getAccountName());
            customerInfo.setPhone(account.getPhone());
            customerInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerInfo.setCreateTime(DateUtil.date());
            customerInfo.setStatus(DataStatus.valid.getKey());
            customerInfo.setCustomerType(account.getCustomerType());
            customerInfo.setRealRemark(account.getRealRemark());
            if (StringUtils.isNotEmpty(account.getCustomerNo())){
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("CUSTOMER_NO", account.getCustomerNo());
                queryWrapper.eq("STATUS", DataStatus.valid.getKey());
                CustomerInfo father = customerInfoMapper.selectOne(queryWrapper);
                if (father != null){
                    customerInfo.setFatherUid(father.getCustomerUid());
                    customerFundService.sendJiFen("invitation",father.getCustomerUid());
                }else{
                    throw new CustomException("没有找到邀请码，请确认邀请码是否正确。");
                }
            }
            customerInfo.setCustomerNo(genCustomerNo());
            customerInfoMapper.insert(customerInfo);
            //初始化资金
            initFund(customerInfo.getCustomerUid());

            customerFundService.sendJiFen("register",customerInfo.getCustomerUid());
        }
        customerUid = customerInfo.getCustomerUid();
        logger.info("\n===========用户信息：{}==============",customerInfo);
        CustomerInfoAccount customerInfoAccount = null;

        //判断是否有账号
        if (ObjectUtil.isEmpty(customerInfoAccount)) {
            customerInfoAccount = new CustomerInfoAccount();
            customerInfoAccount.setCustomerUid(customerUid);
            customerInfoAccount.setAccountName(account.getPhone());
            customerInfoAccount.setAccountNickName(account.getAccountName());
            customerInfoAccount.setAccountPassword(SecurityUtils.encryptPassword(account.getAccountPassword()));
            customerInfoAccount.setRegIp(SecurityUtils.getCustomerClientIp());
            customerInfoAccount.setRegTime(DateUtil.date());
            customerInfoAccount.setPhone(account.getPhone());
            customerInfoAccount.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
            customerInfoAccount.setCreateDate(DateUtil.date());
            customerInfoAccount.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            customerInfoAccount.setSourcePort(SecurityUtils.getCustomerSourcePort());
            logger.info("\n===========创建账号：{}==============",customerInfoAccount);
            customerInfoAccountMapper.insert(customerInfoAccount);
        }
        return true;
    }


    /**
     * 重置密码
     *
     * @param account
     * @return
     */
    @Override
    public Boolean resetCustomerPassword(CustomerInfoAccountVo account) {
        //校验验证码
        PlatformSmsApi platformSmsApi = new PlatformSmsApi();
        platformSmsApi.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        platformSmsApi.setPhone(account.getPhone());
        platformSmsApi.setCode(account.getCode());
        platformSmsConfigService.validateSmsCode(platformSmsApi);
        //验证是否注册过
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        infoAccountQueryWrapper.eq("PHONE", platformSmsApi.getPhone());
        infoAccountQueryWrapper.eq("SOURCE_PORT",SecurityUtils.getCustomerSourcePort());
        CustomerInfoAccount infoAccount = customerInfoAccountMapper.selectOne(infoAccountQueryWrapper);
        if (infoAccount == null) {
            throw new CustomException("该手机号未注册,请先注册");
        }
        infoAccount.setAccountPassword(SecurityUtils.encryptPassword(account.getAccountPassword()));
        infoAccount.setUpdateDate(new Date());
        return customerInfoAccountMapper.updateById(infoAccount)>0;
    }

    /**
     * 产生会员编号
     * @return
     */
    private String genCustomerNo(){
        String key = "Customer_no_"+DateUtils.getYear();
        String rst = DateUtils.getYear()+"";
        Long inc = redisService.incr(key,365L,TimeUnit.DAYS);
        if (inc<10){
            rst += "000"+inc;
        }else if (inc<100){
            rst += "00"+inc;
        }else if (inc<1000){
            rst += "0"+inc;
        }else{
            rst += inc;
        }
        return rst;
    }

    /**
     * 找回密码
     */
    @Override
    public Boolean retrievePwd(CustomerInfoAccountVo account) {
        //校验验证码
        PlatformSmsApi platformSmsApi = new PlatformSmsApi();
        platformSmsApi.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        platformSmsApi.setPhone(account.getPhone());
        platformSmsApi.setCode(account.getCode());
        platformSmsConfigService.validateSmsCode(platformSmsApi);
        QueryWrapper<CustomerInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("PHONE", account.getPhone());
        infoQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        infoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        CustomerInfo info = customerInfoMapper.selectOne(infoQueryWrapper);
        QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
        infoAccountQueryWrapper.eq("CUSTOMER_UID", info.getCustomerUid());
        infoAccountQueryWrapper.eq("SOURCE_PORT", SecurityUtils.getCustomerSourcePort());
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectOne(infoAccountQueryWrapper);
        if(customerInfoAccount!=null){
            customerInfoAccount.setAccountPassword(SecurityUtils.encryptPassword(account.getAccountPassword()));
            customerInfoAccount.setUpdateDate(DateUtil.date());
            customerInfoAccountMapper.updateById(customerInfoAccount);
        }
        return true;
    }


}
